if select(2, UnitClass"player") ~= "DRUID" then return end

local f = CreateFrame("Frame", "JerryLifebloomRoll")

f:SetScript("OnEvent", function (self, event, ...)
	local handler = self[event]
	if handler then handler(self, event, ...) end
end)

local BINDINGS = {
	GetLocale() ~= "frFR" and "Z" or "W",
	"X",
	"C",
	"V",
}

f.mtframes = {}

function f:CreateMTFrame(index)
	if index > #BINDINGS then return end

	local name = "JerryLRButton"..index
	local f = CreateFrame("Button", name, self, "SecureActionButtonTemplate")
	f:SetAttribute("type*", "spell")
	f:SetAttribute("spell1", (GetSpellInfo(33763))) -- Lifebloom
	f:SetAttribute("spell2", (GetSpellInfo(774))) -- Rejuvenation

	self.mtframes[index] = f
end

function f:SetBinding(index)
	local binding = BINDINGS[index]
	if not binding then return end

	local name = "JerryLRButton"..index
	SetOverrideBindingClick(self, true, binding, name, "LeftButton")
	SetOverrideBindingClick(self, true, "SHIFT-"..binding, name, "RightButton")
end


function f:DisableMTFrame(index)
	local f = self.mtframes[index]
	if not f then return end
	f:SetAttribute("unit", "")
end

function f:UpdateMTFrame(index, name)
	local f = self.mtframes[index]
	if not f then return end
	for i = 1, 40 do
		local unit = "raid"..i
		if UnitName(unit) == name then
			f:SetAttribute("unit", unit)
			return
		end
	end
--~ 	DEFAULT_CHAT_FRAME:AddMessage(self:GetName().." unable to find "..name)
	f:SetAttribute("unit", "")
end

function f:MainTankUpdate()
	if InCombatLockdown() then
		self.need_update = true
		return
	end
	local mt = oRA.maintanktable
	if not mt then
		for i = 1, #self.mtframes do
			self:DisableMTFrame(i)
		end
	else
		for i = #self.mtframes + 1, #mt do
			self:CreateMTFrame(i)
		end
		for i = #mt + 1, #self.mtframes do
			self:DisableMTFrame(i)
		end
		for i, name in ipairs(mt) do
			self:UpdateMTFrame(i, name)
		end
	end
end
f.RAID_ROSTER_UPDATE = f.MainTankUpdate

function f:PLAYER_REGEN_ENABLED()
	ClearOverrideBindings(self)
	if self.need_update then
		self:MainTankUpdate()
		self.need_update = nil
	end
end

function f:PLAYER_REGEN_DISABLED()
	for i = 1, #self.mtframes do
		self:SetBinding(i)
	end
end

function f:ADDON_LOADED(_, addon)
	if addon == "oRA2" then
		self:UnregisterEvent"ADDON_LOADED"
		self.ADDON_LOADED = nil
		AceLibrary("AceEvent-2.0").RegisterEvent(self, "oRA_MainTankUpdate", "MainTankUpdate")
		self:MainTankUpdate()
		self:RegisterEvent"PLAYER_REGEN_ENABLED"
		self:RegisterEvent"PLAYER_REGEN_DISABLED"
		self:RegisterEvent"RAID_ROSTER_UPDATE"
	end
end

if IsAddOnLoaded"oRA2" then
	f:ADDON_LOADED(nil, "oRA2")
else
	f:RegisterEvent"ADDON_LOADED"
end

SlashCmdList.JERRY_BLOOMROLL = function ()
	for i, frame in ipairs(JerryLifebloomRoll.mtframes) do
		local unit = frame:GetAttribute("unit")
		local name = UnitName(unit)
		DEFAULT_CHAT_FRAME:AddMessage(("Lifebloom roll %d: %s %s (%s)"):format(i, unit or "", name or "", BINDINGS[i] or ""))
	end
end
SLASH_JERRY_BLOOMROLL1="/bloomroll"
